
gulp = require 'gulp'
gutil = require 'gutil'
_ = require 'lodash'

ngmin = require 'gulp-ngmin'
coffee = require 'gulp-coffee'
concat = require 'gulp-concat'
uglify = require 'gulp-uglify'
assets = require 'gulp-assets'
filter = require 'gulp-filter'
connect = require 'gulp-connect'
minifyCSS = require 'gulp-minify-css'
minifyHTML = require 'gulp-minify-html'
htmlReplace = require 'gulp-html-replace'
sourcemaps = require 'gulp-sourcemaps'

path =
  coffee:
    src: './app/scripts/**/*.coffee'
    dest: './app/scripts/'
  coffeeMap:
    src: ['config', 'controllers', 'directives', 'filters', 'services', '']

gulp.task 'coffeeMap', () ->
  _.each path.coffeeMap.src, (e) ->
    src = "./app/scripts/#{e}/*.coffee"
    gulp.src src
      .pipe sourcemaps.init()
      .pipe coffee().on 'error', gutil.log
      .pipe sourcemaps.write "./"
      .pipe gulp.dest "./app/js/" + e

gulp.task 'watch', () ->
  gulp.watch path.coffee.src, ['coffeeMap']

gulp.task 'buildScript', ['coffeeMap'], () ->
  gulp.src path.coffee.src
    .pipe coffee().on 'error', gutil.log
    .pipe ngmin()
    .pipe uglify()
    .pipe concat 'app.js'
    .pipe gulp.dest './dist/js/'

gulp.task 'buildBower', () ->
  fn = filter (f) ->
    console.log f.path
    yes
  gulp.src "./app/index.html"
    .pipe assets
      js: yes
      css: no
    .pipe uglify()
    #.pipe(filter('!scripts/**/*.js'))
    .pipe concat 'vendor.js'
    #.pipe(fn)
    .pipe gulp.dest './dist/js/'

gulp.task 'buildCss', () ->
  gulp.src "./app/index.html"
    .pipe assets
      js: no
      css: yes
    .pipe minifyCSS keepBreaks:true
    .pipe concat 'style.css'
    .pipe gulp.dest './dist/css/'

gulp.task 'buildResource', () ->
  gulp.src './app/bower_components/bootstrap/dist/fonts/*'
    .pipe gulp.dest './dist/fonts/'

  gulp.src './app/images/**'
    .pipe gulp.dest './dist/images/'

  gulp.src './app/*.ico'
    .pipe gulp.dest './dist/'

gulp.task 'buildHtml', () ->
  opt =
    empty: yes
    spare: yes
    quotes: yes
    conditionals: yes
    comments:yes

  gulp.src('./app/views/**/*.html')
    #.pipe(minifyHTML(opt))
    .pipe(gulp.dest('./dist/views/'))

  i = Math.round Math.random() * 1000000
  varDic =
    css: "css/style.css?#{i}"
    jsVendor: "js/vendor.js?#{i}"
    jsApp: "js/app.js?#{i}"

  gulp.src('./app/index.html')
    .pipe(htmlReplace(varDic))
    .pipe(gulp.dest('./dist/'))

  gulp.src('./app/token.html')
    .pipe(htmlReplace(varDic))
    .pipe(gulp.dest('./dist/'))


gulp.task 'test', ['buildScript', 'buildBower']

gulp.task 'default', ['coffeeMap', 'watch'], () ->

gulp.task 'build', ['buildScript', 'buildBower', 'buildCss', 'buildHtml', 'buildResource'], () ->

gulp.task 'b', ['build']
gulp.task 'w', ['default']
